<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="数据源名称" prop="datasourceName">
        <el-input
          v-model="queryParams.datasourceName"
          placeholder="请输入数据源名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源编码" prop="datasourceCode">
        <el-input
          v-model="queryParams.datasourceCode"
          placeholder="请输入数据源编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源类型" prop="datasourceType">
        <el-select v-model="queryParams.datasourceType" placeholder="请选择数据源类型" clearable size="small">
          <el-option label="MySQL" value="mysql" />
          <el-option label="Oracle" value="oracle" />
          <el-option label="SQL Server" value="sqlserver" />
          <el-option label="PostgreSQL" value="postgresql" />
          <el-option label="Redis" value="redis" />
          <el-option label="MongoDB" value="mongodb" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:datasource:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:datasource:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="small"
          @click="handleRefresh"
          v-hasPermi="['system:datasource:refresh']"
        >刷新数据源</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-export"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:datasource:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据源编号" prop="datasourceId" width="80" align="center" />
      <el-table-column label="数据源名称" prop="datasourceName" :show-overflow-tooltip="true" />
      <el-table-column label="数据源编码" prop="datasourceCode" width="120" align="center" />
      <el-table-column label="数据源类型" prop="datasourceType" width="100" align="center">
        <template slot-scope="scope">
          {{ getDatasourceTypeName(scope.row.datasourceType) }}
        </template>
      </el-table-column>
      <el-table-column label="驱动类名" prop="driverClassName" :show-overflow-tooltip="true" />
      <el-table-column label="连接URL" prop="url" :show-overflow-tooltip="true" />
      <el-table-column label="用户名" prop="username" width="100" />
      <el-table-column label="状态" prop="status" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['system:datasource:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" align="center" />
      <el-table-column label="操作" width="160" align="center" class="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:datasource:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['system:datasource:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleStatus(scope.row)"
            v-hasPermi="['system:datasource:status']"
          >状态</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据源名称" prop="datasourceName">
              <el-input v-model="form.datasourceName" placeholder="请输入数据源名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据源编码" prop="datasourceCode">
              <el-input v-model="form.datasourceCode" placeholder="请输入数据源编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据源类型" prop="datasourceType">
              <el-select v-model="form.datasourceType" placeholder="请选择数据源类型" @change="handleTypeChange">
                <el-option label="MySQL" value="mysql" />
                <el-option label="Oracle" value="oracle" />
                <el-option label="SQL Server" value="sqlserver" />
                <el-option label="PostgreSQL" value="postgresql" />
                <el-option label="Redis" value="redis" />
                <el-option label="MongoDB" value="mongodb" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="驱动类名" prop="driverClassName">
          <el-input v-model="form.driverClassName" placeholder="请输入驱动类名" />
        </el-form-item>
        <el-form-item label="连接URL" prop="url">
          <el-input v-model="form.url" type="textarea" placeholder="请输入连接URL" :rows="2" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="初始连接数" prop="initialSize">
              <el-input-number v-model="form.initialSize" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最小连接数" prop="minIdle">
              <el-input-number v-model="form.minIdle" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大连接数" prop="maxActive">
              <el-input-number v-model="form.maxActive" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="最大等待时间(ms)" prop="maxWait">
          <el-input-number v-model="form.maxWait" :min="1000" :max="300000" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleTestConnection">测试连接</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 数据源状态对话框 -->
    <el-dialog
      title="数据源状态"
      :visible.sync="statusOpen"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="数据源名称">{{ statusData.datasourceName }}</el-descriptions-item>
        <el-descriptions-item label="数据源编码">{{ statusData.datasourceCode }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ statusData.state }}</el-descriptions-item>
        <el-descriptions-item label="活跃连接数">{{ statusData.activeCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="空闲连接数">{{ statusData.poolingCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最大连接数">{{ statusData.maxActive || 0 }}</el-descriptions-item>
        <el-descriptions-item label="初始连接数">{{ statusData.initialSize || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最小空闲连接">{{ statusData.minIdle || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最大等待时间(ms)">{{ statusData.maxWait || 0 }}</el-descriptions-item>
        <el-descriptions-item label="等待线程数">{{ statusData.waitThreadCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="连接错误数" :span="2">{{ statusData.connectErrorCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">{{ statusData.errorMsg || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listDatasource, getDatasource, delDatasource, addDatasource, updateDatasource, testDatasourceConnection, refreshDatasource, getDatasourceStatus } from "@/api/system/datasource";

export default {
  name: "Datasource",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 数据源配置表格数据
      datasourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态对话框
      statusOpen: false,
      statusData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        datasourceName: undefined,
        datasourceCode: undefined,
        datasourceType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        datasourceName: [
          { required: true, message: "数据源名称不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "数据源名称长度不能超过100个字符", trigger: "blur" }
        ],
        datasourceCode: [
          { required: true, message: "数据源编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "数据源编码长度不能超过50个字符", trigger: "blur" }
        ],
        datasourceType: [
          { required: true, message: "数据源类型不能为空", trigger: "change" }
        ],
        driverClassName: [
          { required: true, message: "驱动类名不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "连接URL不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      // 数据源类型配置
      datasourceTypeConfig: {
        mysql: {
          driver: "com.mysql.cj.jdbc.Driver",
          urlTemplate: "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8"
        },
        oracle: {
          driver: "oracle.jdbc.OracleDriver",
          urlTemplate: "jdbc:oracle:thin:@localhost:1521:ORCL"
        },
        sqlserver: {
          driver: "com.microsoft.sqlserver.jdbc.SQLServerDriver",
          urlTemplate: "jdbc:sqlserver://localhost:1433;DatabaseName=test"
        },
        postgresql: {
          driver: "org.postgresql.Driver",
          urlTemplate: "jdbc:postgresql://localhost:5432/test"
        }
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据源配置列表 */
    getList() {
      this.loading = true;
      listDatasource(this.queryParams).then(response => {
        this.datasourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询数据源类型名称 */
    getDatasourceTypeName(type) {
      const typeMap = {
        mysql: "MySQL",
        oracle: "Oracle",
        sqlserver: "SQL Server",
        postgresql: "PostgreSQL",
        redis: "Redis",
        mongodb: "MongoDB"
      };
      return typeMap[type] || type;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增数据源配置";
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      getDatasource(row.datasourceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据源配置";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      getDatasource(row.datasourceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看数据源配置";
        // 禁用表单
        this.$nextTick(() => {
          this.$refs.form.fields.forEach(field => {
            field.disabled = true;
          });
        });
      });
    },
    /** 状态按钮操作 */
    handleStatus(row) {
      getDatasourceStatus(row.datasourceCode).then(response => {
        this.statusData = { ...row, ...response.data };
        this.statusOpen = true;
      });
    },
    /** 状态变更 */
    handleStatusChange(row) {
      const text = row.status === "0" ? "启用" : "停用";
      this.$confirm(`确认要${text}该数据源吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateDatasource(row).then(response => {
          this.msgSuccess(`${text}成功`);
          this.getList();
        }).catch(() => {
          row.status = row.status === "0" ? "1" : "0";
        });
      }).catch(() => {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 测试连接 */
    handleTestConnection() {
      this.$refs.form.validate(valid => {
        if (valid) {
          testDatasourceConnection(this.form).then(response => {
            // 显示后端返回的详细结果，如果有
            if (response && response.data) {
              this.$modal.msgSuccess("连接成功：" + JSON.stringify(response.data));
            } else {
              this.$modal.msgSuccess("连接成功");
            }
          }).catch(error => {
            // 显示错误详情
            let errorMsg = "连接失败，请检查配置信息";
            if (error.response && error.response.data && error.response.data.msg) {
              errorMsg += "，" + error.response.data.msg;
            }
            // this.$modal.msgError(errorMsg);
          });
        }
      });
    },
    /** 刷新数据源 */
    handleRefresh() {
      this.$confirm("确认要刷新所有数据源吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        refreshDatasource().then(response => {
          this.$modal.msgSuccess("刷新成功");
          this.getList();
        }).catch(() => {
          this.$modal.msgError("刷新失败");
        });
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        datasourceId: undefined,
        datasourceName: undefined,
        datasourceCode: undefined,
        datasourceType: undefined,
        driverClassName: undefined,
        url: undefined,
        username: undefined,
        password: undefined,
        status: "0",
        initialSize: 5,
        minIdle: 10,
        maxActive: 20,
        maxWait: 60000,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.datasourceId != undefined) {
            updateDatasource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDatasource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.statusOpen = false;
      this.reset();
      // 恢复表单禁用状态
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.fields.forEach(field => {
            field.disabled = false;
          });
        }
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.datasourceId);
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const datasourceIds = row ? [row.datasourceId] : this.ids;
      this.$confirm(`确认要删除选中的${datasourceIds.length}条数据源吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delDatasource(datasourceIds).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("确认要导出所有数据源配置数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.location.href = process.env.VUE_APP_BASE_API + "/system/datasource/export?" + this.tansParams(queryParams);
      });
    },
    /** 数据源类型变更 */
    handleTypeChange(type) {
      const config = this.datasourceTypeConfig[type];
      if (config) {
        this.form.driverClassName = config.driver;
        this.form.url = config.urlTemplate;
      }
    }
  }
};
</script>
